//
//  ZJKEmoticonToolBar.swift
//  MicroBlog
//
//  Created by VAD on 16/4/27.
//  Copyright © 2016年 朱江坤. All rights reserved.
//

import UIKit

enum ZJKEmotionType: Int {
    
    case Recent = 0, Default, Emoji, Lxh
}

class ZJKEmoticonToolBar: UIStackView {

 
    var lastSelectButton: UIButton?
    
    // 点击表情类型按钮要执行的闭包
    var emoticonButtonClickClosure: ((type: ZJKEmotionType)->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        distribution = .FillEqually
        
        // 添加4个按钮
        addChildButton("最近", bgImgNamed: "compose_emotion_table_left", type: .Recent)
        addChildButton("默认", bgImgNamed: "compose_emotion_table_mid", type: .Default)
        addChildButton("Emoji", bgImgNamed: "compose_emotion_table_mid", type: .Emoji)
        addChildButton("浪小花", bgImgNamed: "compose_emotion_table_right", type: .Lxh)
    }
    
    private func addChildButton(title: String, bgImgNamed: String, type: ZJKEmotionType){
        
        let button = UIButton()
        
        // 添加点击事件
        button.addTarget(self, action: "childButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
        // 设置tag
        button.tag = type.rawValue
        // 设置文字以及字体大小
        button.titleLabel?.font = UIFont.systemFontOfSize(14)
        button.setTitle(title, forState: UIControlState.Normal)
        
        // 设置不同状态下的文字颜色
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
        
        // 设置不同状态的背景图片
        button.setBackgroundImage(UIImage(named: "\(bgImgNamed)_normal"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "\(bgImgNamed)_selected"), forState: UIControlState.Selected)
        
        // 添加到stackView里面
        addArrangedSubview(button)
        
    }
    
    
    @objc private func childButtonClick(button: UIButton) {
        
        // 如果用户点击的按钮就是当前选中的按钮的话就不执行逻辑
        if lastSelectButton == button {
            return
        }
        
        // 取消选中之前的按钮
        lastSelectButton?.selected = false
        // 选中当前的按钮
        button.selected = true
        // 重新记录一下
        lastSelectButton = button
        // 执行闭包
        emoticonButtonClickClosure?(type: ZJKEmotionType(rawValue: button.tag)!)
    }


}
